import { Http } from "./http";

class Paging {
    offset
    limit
    req
    url
    locker = false
    moreData = true
    accumulator = []
    constructor(req, limit = 10, offset = 0) {
        this.offset = offset
        this.limit = limit
        this.req = req
        this.url = req.url
    }
    async getMoreData() {
        if (!this.moreData) {
            return
        }
        if (!this._getLocker()) {
            return
        }
        const data = await this._actualGetData()
        this._releaseLocker()
        return data
    }
    async  _actualGetData() {
        const req = this._getCurrentReq()
        let paging = await Http.request(req)
        if (!paging) {
            return null
        }
        if (paging.total === 0) {
            return {
                empty: true,
                items: [],
                moreData: false,
                accumulator: []
            }
        }
        this.moreData = Paging._moreData(paging.total, this.offset)
        if (this.moreData) {
            this.offset += this.limit
        }
        this._accumulator(paging.rows)
        return {
            empty: false,
            items: paging.rows,
            moreData: this.moreData,
            accumulator: this.accumulator
        }
    }
    _accumulator(items) {
        this.accumulator = this.accumulator.concat(items)
    }
    static _moreData(totalPage, pageNum) {
        return pageNum < totalPage - 1
    }
    _getCurrentReq() {
        let url = this.url
        const params = `offset=${this.offset}&limit=${this.limit}`
        if (url.includes('?')) {
            url += '&' + params
        } else {
            url += '?' + params
        }
        this.req.url = url
        return this.req
    }
    _getLocker() {
        if (this.locker) {
            return false
        }
        this.locker = true
        return true
    }
    _releaseLocker() {
        this.locker = false
    }
}
export {
    Paging
}